#include "/home/zhong/muduo/muduo/net/TcpClient.h"
#include "/home/zhong/muduo/muduo/net/EventLoopThread.h"
#include "/home/zhong/muduo/muduo/net/TcpConnection.h"
#include "/home/zhong/muduo/muduo/base/CountDownLatch.h"

#include <iostream>
#include <functional>
#include <string>
#include <memory>

class TranslateClient
{
private:
    // 注意这里的类内成员函数参数会多一个this
    void OnConnection(const muduo::net::TcpConnectionPtr &conn) // 链接建立时发生的回调函数
    {
        if (conn->connected() == true)
        {
            std::cout << "connection success" << std::endl;
            // 连接建立成功时需要唤醒当前的阻塞态
            _latch.countDown();
            _conn = conn; // 设置类内的Connection
        }
        else
        {
            std::cout << "connection closed" << std::endl;
        }
    }
    void OnMessage(const muduo::net::TcpConnectionPtr &conn, muduo::net::Buffer *buff, muduo::Timestamp) // 事件发生时进行处理的回调函数
    {
        std::cout << "translate result: " << buff->retrieveAllAsString() << std::endl;
    }

public:
    TranslateClient(const std::string &server_ip, int server_port)
        : _latch(1), _client(_loop_thread.startLoop(), muduo::net::InetAddress(server_ip, server_port), "TranslateCilent")
    {
        auto OnConnection = std::bind(&TranslateClient::OnConnection, this, std::placeholders::_1);
        _client.setConnectionCallback(OnConnection);
        auto OnMessage = std::bind(&TranslateClient::OnMessage, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
        _client.setMessageCallback(OnMessage);
    }

    void connect()
    {
        _client.connect();
        _latch.wait(); // 进行阻塞等待，直到连接建立成功
    }
    bool send(const std::string &mesg)
    {
        if (_conn->connected() == true)
        {
            _conn->send(mesg);
            return true;
        }
        else
        {
            return false;
        }
    }

private:
    muduo::CountDownLatch _latch;             // 实现了线程同步，主要是用于等待连接完成后再进行其他操作
    muduo::net::EventLoopThread _loop_thread; // 自动开始实时进行线程的监控，进入阻塞态
    muduo::net::TcpClient _client;
    muduo::net::TcpConnectionPtr _conn;
};

int main()
{
    std::unique_ptr<TranslateClient> tc = std::make_unique<TranslateClient>("127.0.0.1", 8080);
    tc->connect();
    while (1)
    {
        std::string buffer;
        std::cin >> buffer;
        tc->send(buffer);
    }
}